﻿// ***QualifyLeadDD*** 
// 
// Drew Thompson, Microsoft CRM SDK Escalation Engineer
//
//
// Microsoft Disclaimer:
// THIS PROGRAM SOURCE CODE IS PROVIDED "AS IS" WITHOUT WARRANTY 
// REPRESENTATION OR CONDITION OF ANY KIND EITHER EXPRESS OR IMPLIED, 
// INCLUDING BUT NOT LIMITED TO CONDITIONS OR OTHER TERMS OF 
// MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. THE USER 
// ASSUMES THE ENTIRE RISK AS TO THE ACCURACY AND THE USE OF THIS 
// PROGRAM CODE OR RESULTING EXECUTABLE CODE.
//

// Plug-in Registration
// Message: QualifyLead
// Primary Entity: lead
// Eventing Pipeline Stage of Execution: Pre-operation
// Execution Mode: Synchronous

// References from SDK Bin
// microsoft.xrm.sdk.dll
// microsoft.crm.sdk.proxy.dll

// .NET references
// System.runtime.serialization
// System.runtime.serialization.Formatters.Soap
// System.servicemodel

// NOTE
// If this is a new C# project make sure you change the version of .NET in project properties
// to .Net Framework 4

// Std usings for console
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// Added usings for CRM
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages; 
using Microsoft.Xrm.Sdk.Query;
using System.ServiceModel;
using System.ServiceModel.Description;

// Namespace for GenteratedCode.cs
// crmsvcutil /url:http://<Your org URI here>/<org>/XRMServices/2011/Organization.svc /username:administrator /password:xxxx /domain:dddd /serviceContextName:svcContext /namespace:earlyProxy /out:GenreatedCode.cs
using earlyProxy;

namespace QualifyLeadDD
{
    public class QualifyLeadDD : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context from the service provider.
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
                serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

            // Turn off duplicate detection for this update as we are going to do it ourselves
            context.InputParameters["SuppressDuplicateDetection"] = true;  

            // Obtain the organization service reference.
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("CreateContact")) 
            {
                // Obtain the target entity from the input parmameters.
                string leadidguid = ((EntityReference)context.InputParameters["LeadId"]).Id.ToString();
                Guid leadid = new Guid(leadidguid);

                Lead lead = (Lead)service.Retrieve(
                "lead",
                leadid,
                new ColumnSet("leadid", "lastname")
                );
                
                if (lead.LogicalName == "lead")
                {
                     //Check for duplicates
                    QueryExpression Query = new QueryExpression()
                    {
                        EntityName = Contact.EntityLogicalName,
                        ColumnSet = new ColumnSet("lastname"),
                        Criteria =
                        {
                            Conditions =
                            {
                                new ConditionExpression("lastname", ConditionOperator.Equal, lead.LastName)
                            }
                        }
                    };
                    DataCollection<Entity> dc = service.RetrieveMultiple(Query).Entities;

                    if (dc.Count > 0)
                    {
                        string duplicatename = "";
                        foreach(Contact contact in dc)
                        {
                            duplicatename = duplicatename + contact.LastName + " ";
                        }
                        {
                            throw new InvalidPluginExecutionException("A duplicate contact was detected " + duplicatename);
                        }
                    }
                 }
            }
        }
    }
}
